package com.cola.custSpeechTranscription.model;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @BelongsProject: custSpeechTranscription
 * @BelongsPackage: com.cola.custSpeechTranscription.model
 * @Author: jiangkang
 * @CreateTime: 2025-10-30  15:09
 * @Description: TODO
 * @Version: 1.0
 */
public class UserSession {
    private final String userId;
    private WebSocketSession audioSession;
    private CustShareSession shareSession;
    private final List<String> transcripts = new CopyOnWriteArrayList<>();
    private final long createTime = System.currentTimeMillis();
    private long lastActivityTime = System.currentTimeMillis();

    private static final Logger log = LoggerFactory.getLogger("LCAP_EXTENSION_LOGGER");

    public UserSession(String userId, WebSocketSession audioSession) {
        this.userId = userId;
        this.audioSession = audioSession;
        updateActivityTime();
    }

    public void setAudioSession(WebSocketSession audioSession) {
        this.audioSession = audioSession;
        if (audioSession != null) {
            updateActivityTime();
        }
    }

    public void setShareSession(CustShareSession shareSession) {
        this.shareSession = shareSession;
        if (shareSession != null) {
            updateActivityTime();
        }
    }

    public boolean isIdle() {
        return audioSession == null && shareSession == null;
    }

    public void addTranscript(String transcript) {
        transcripts.add(transcript);
        updateActivityTime();

        // 限制历史记录数量，防止内存溢出
        if (transcripts.size() > 1000) {
            transcripts.remove(0);
        }
    }

    /**
     * 清除所有转录历史
     */
    public void clearTranscripts() {
        this.transcripts.clear();
    }

    public void sendMessageToAudioSession(String message) {
        if (audioSession != null && audioSession.isOpen()) {
            try {
                audioSession.sendMessage(new TextMessage(message));
            } catch (IOException e) {
                log.error("[发送消息到音频会话] 失败 userId={}", userId, e);
            }
        }
    }

    private void updateActivityTime() {
        this.lastActivityTime = System.currentTimeMillis();
    }

    // Getters
    public String getUserId() { return userId; }
    public WebSocketSession getAudioSession() { return audioSession; }
    public CustShareSession getShareSession() { return shareSession; }
    public List<String> getTranscripts() { return transcripts; }
    public long getLastActivityTime() { return lastActivityTime; }
    public long getCreateTime() { return createTime; }
}